<template>
  <div class="artilce-list">
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <Article-item
          v-for="(item, index) in articles"
          :key="index"
          :article="item"
        ></Article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import { getArticles } from "@/api/article";
import ArticleItem from "./article-item";
export default {
  name: "ArtilceList",
  props: {
    channel: {
      type: Object,
      require: true,
    },
  },
  components: {
    ArticleItem,
  },
  data() {
    return {
      articles: [],
      loading: false,
      finished: false,
      timestamp: 1556789000001,
      isLoading: false, //下拉刷新状态
      refreshSuccessText: "",
    };
  },
  methods: {
    async onLoad() {
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: this.timestamp || Date.now(), //时间戳，请求新的推荐数据传当前的时间戳，请求历史推荐传指定的时间戳 timestamp就是相当于页码，请求最新数据时间戳，下一页数据使用上一次返回的数据中的时间戳
        with_top: 1, //是否包含置顶，进入页面第一次请求时要包含置顶文章，1-包含置顶，0-不包含
      });
      const { results } = data.data;
      this.articles.push(...results);
      this.loading = false;
      //   数据全部加载完成
      if (results.length) {
        //   更新获取下一页数据的页码
        this.timestamp = data.data.pre_timestamp;
      } else {
        //   没有数据了，把加载状态设置结束，不再触发加载更多
        this.finished = true;
      }
    },
    async onRefresh() {
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: Date.now(),
        with_top: 1,
      });
      const { results } = data.data;
      this.articles.unshift(...results);
      this.isLoading = false;
      this.refreshSuccessText = `更新了${results.length}数据`;
    },
  },
};
</script>
<style lang="less" scoped>
.artilce-list {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 50px;
  top: 90px;
  overflow: auto;
}
</style>
